/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { PureComponent, Fragment } from "react";
import {
  Button,
  Modal,
  Row,
  Col,
  Form,
  Select,
  Input,
  message,
  Radio,
  Checkbox,
  Tooltip,
  Alert,
  Spin,
  Pagination,
} from "antd";
import { connect } from "dva";
import styles from "./index.less";

const CheckboxGroup = Checkbox.Group;
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const Option = Select.Option;
const SearchForm = Form.create()(props => {
  const {
    searching,
    onSearch,
    wxList,
    form: { getFieldDecorator, getFieldsValue },
  } = props;
  const spholder = "请输入业务员姓名或手机号";
  const handleSubmit = () => {
    const { search, wxid } = getFieldsValue();
    const { iu_id, uid, platform, open_platform } = wxList.filter(
      item => item.open_platform == wxid
    )[0];
    if (onSearch) {
      onSearch({ iu_id, uid, platform, open_platform, search: search });
    }
  };
  return (
    <Form
      layout="inline"
      onSubmit={e => {
        e.preventDefault();
        handleSubmit();
      }}
    >
      <FormItem>
        {getFieldDecorator("wxid", {
          initialValue: wxList[0].open_platform,
        })(
          <Select placeholder="请选择公众号" style={{ width: 140 }}>
            {wxList.map(item => (
              <Option
                key={item.open_platform}
                value={item.open_platform}
                title={item.open_platform_name}
              >
                {item.open_platform_name}
              </Option>
            ))}
          </Select>
        )}
      </FormItem>
      <FormItem>
        {getFieldDecorator("search")(<Input style={{ width: 200 }} placeholder={spholder} />)}
      </FormItem>
      <FormItem>
        <Button loading={searching} icon="search" htmlType="submit" type="primary">
          查询
        </Button>
      </FormItem>
    </Form>
  );
});

@connect(({ loading, station, operator_wx }) => ({
  getting_wx: loading.effects["operator_wx/getWxList"],
  getting_c: loading.effects["operator_wx/getWxCourierList"],
  importting: loading.effects["operator_wx/importCourier"],
  getting_s: loading.effects["station/getStationList"],
  getting_q: loading.effects["operator_wx/getAuthQrcode"],
  operator_wx,
  stationList: station.list,
}))
class ImportCourier extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectedCourier: null,
      courierList: {
        enable: [],
        disabled: [],
      },
    };
  }

  // 分类保存数据
  assortByDisabled = data => {
    const courierList = {
      enable: [],
      disabled: [],
    };
    if (data && data.list) {
      const { page, list, total, size } = data;
      list.map(item => {
        const { courier_phone, is_exists, courier_name = "" } = item;
        const disabled = is_exists == 1;
        const data = {
          disabled,
          label: `${disabled ? "*" : ""}${courier_name}（${courier_phone}）`,
          value: courier_phone,
        };
        if (!disabled) {
          courierList.enable.push(data);
        } else {
          courierList.disabled.push(data);
        }
      });
      this.setState({
        selectedCourier: null,
        selectedStation: null,
        courierList,
        pagination: {
          total: 1 * total,
          pageSize: 1 * size,
          current: 1 * page,
        },
      });
    }
  };

  // 关闭弹窗
  handleCancel = () => {
    this.setState({
      visible: false,
    });
  };

  // 立即导入
  handleOk = () => {
    const { selectedCourier, selectedStation, courierList } = this.state;
    if (!selectedCourier || selectedCourier.length === 0) {
      message.error("请勾选要导入的业务员");
      return;
    }
    if (!selectedStation) {
      message.error("请勾选分配的站点");
      return;
    }
    const { dispatch } = this.props;
    dispatch({
      type: "operator_wx/importCourier",
      payload: {
        courier_phone: selectedCourier,
        company_site_id: selectedStation,
      },
      then: res => {
        if (res.code == 0) {
          this.handlePageChange(1);
        }
      },
    });
  };

  // 触发搜索
  handleSearch = data => {
    this.getWxCourierList({
      page: 1,
      ...data,
    });
  };

  // 翻页
  handlePageChange = page => {
    this.getWxCourierList({
      ...this.currentWx,
      page,
    });
  };

  // 获取二维码
  getAuthQrcode = () => {
    this.props.dispatch({
      type: "operator_wx/getAuthQrcode",
      payload: "",
    });
  };

  //获取微信快递员
  getWxCourierList = data => {
    const { dispatch } = this.props;
    this.currentWx = data;
    dispatch({
      type: "operator_wx/getWxCourierList",
      payload: {
        ...data,
      },
      then: ({ code, data }) => {
        if (code == 0 && data) {
          this.assortByDisabled(data);
        }
      },
    });
  };

  // 获取微信公众号列表
  getWxList = () => {
    const { dispatch } = this.props;
    this.title = "定制公众号绑定";
    dispatch({
      // 测试使用
      // payload: {
      //   bind: true,
      // },
      type: "operator_wx/getWxList",
      then: ({ code, data }) => {
        let wxList = null;
        if (code == 0 && data) {
          this.title = "导入定制公众号业务员";
          wxList = data.list;
        }
        this.setState(
          {
            visible: true,
          },
          () => {
            if (wxList && wxList.length > 0) {
              // 获取快递员列表
              const { iu_id, uid, platform, open_platform } = wxList[0];
              this.getWxCourierList({
                iu_id,
                uid,
                platform,
                open_platform,
              });
            } else {
              // 获取绑定二维码
              this.getAuthQrcode();
            }
          }
        );
      },
    });
  };

  // 选择站点
  handleRadioChange = e => {
    this.setState({
      selectedStation: e.target.value,
    });
  };

  // 业务员勾选切换
  handleChange = selectedCourier => {
    this.setState({
      selectedCourier,
    });
  };

  // 全选业务员
  handleAllChange = e => {
    const { checked } = e.target;
    const selectedCourier = this.state.courierList.enable.map(item => item.value);
    this.setState({
      selectedCourier: checked ? selectedCourier : null,
    });
  };

  render() {
    const {
      getting_c,
      getting_s,
      getting_q,
      getting_wx,
      importting,
      stationList,
      searching,
      operator_wx: { wxList, qrcodeData },
    } = this.props;
    const { courierList, selectedStation, selectedCourier, visible, pagination } = this.state;
    const enableLength = courierList.enable.length;
    const selectedLength = selectedCourier ? selectedCourier.length : 0;
    const allChecked = selectedLength && selectedLength === enableLength;
    const indeterminate = !allChecked && selectedLength;
    const hasWxList = !!wxList && wxList.length;
    return (
      <Fragment>
        <Button loading={getting_wx} icon="select" type="primary" onClick={this.getWxList}>
          导入定制公众号业务员
        </Button>
        <Modal
          width={600}
          distery
          footer={
            hasWxList ? (
              <Button loading={importting} onClick={this.handleOk} type="primary">
                立即导入
              </Button>
            ) : null
          }
          onCancel={this.handleCancel}
          title={this.title}
          centered
          visible={visible}
        >
          {hasWxList ? (
            <div className={styles.import}>
              <Alert
                type="warning"
                banner
                message="注：业务员前面带*的为已存在或者已导入的业务员，不可导入！"
              />
              <SearchForm loading={searching} onSearch={this.handleSearch} wxList={wxList} />
              <Row gutter={16}>
                <Col sm={12}>
                  <div className="import-box">
                    <p>
                      <Checkbox
                        disabled={enableLength === 0}
                        indeterminate={indeterminate}
                        onChange={this.handleAllChange}
                        checked={allChecked}
                        value="all"
                      >
                        待导入的业务员
                      </Checkbox>
                    </p>
                    <Spin spinning={getting_c}>
                      <CheckboxGroup
                        value={selectedCourier}
                        options={[...courierList.enable, ...courierList.disabled]}
                        onChange={this.handleChange}
                      />
                      {pagination && (
                        <Pagination
                          style={{ textAlign: "center", padding: "16px 0" }}
                          onChange={this.handlePageChange}
                          simple
                          {...pagination}
                        />
                      )}
                    </Spin>
                  </div>
                </Col>
                <Col sm={12}>
                  <div className="import-box">
                    <p>选择分配的站点</p>
                    <Spin spinning={getting_s}>
                      <RadioGroup value={selectedStation} onChange={this.handleRadioChange}>
                        {stationList &&
                          stationList.map(item => {
                            const { site_name, site_id } = item;
                            return (
                              <Radio key={site_id} value={site_id}>
                                <Tooltip placement="right" title={site_name}>
                                  {site_name.length > 14
                                    ? `${site_name.substring(0, 14)}...`
                                    : site_name}
                                </Tooltip>
                              </Radio>
                            );
                          })}
                      </RadioGroup>
                    </Spin>
                  </div>
                </Col>
              </Row>
            </div>
          ) : (
            <Row gutter={16}>
              <Col sm={12}>
                <Spin spinning={getting_q}>
                  <img src={qrcodeData && qrcodeData.url} className={styles.qrcode} />
                </Spin>
              </Col>
              <Col sm={12}>
                <p>
                  当前快宝智慧快递管理平台未存在绑定的定制公众号，定制公众号可通过扫描左侧二维码绑定快宝智慧快递管理平台。
                </p>
                <p style={{ color: "red" }}>
                  注：绑定成功后关闭此界面再次点击“导入定制公众号业务员”可导入定制公众号业务员。
                </p>
              </Col>
            </Row>
          )}
        </Modal>
      </Fragment>
    );
  }
}

export default ImportCourier;
